package controller;

import cn.edu.zut.model.Reader;
import cn.edu.zut.model.User;
import cn.edu.zut.service.ReaderServiceImpl;
import cn.edu.zut.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
public class ReaderController {

    @Autowired
    ReaderServiceImpl readerService;
    @Autowired
    UserServiceImpl userService;
    //读者信息注册
    @RequestMapping(value = "readerRegister",method = RequestMethod.POST)
    public ModelAndView readerRegister(Reader reader,User user,HttpSession session){

        List<User> users=userService.selectAllUser();
        for(User user1:users){
            if(user.getName().equals(user1.getName())||user.getName().equals("")){
                return new ModelAndView("readerRegister","message","用户名重复，请更换用户名");
            }
        }
        userService.insertUser(user);
        List<Reader> readers=readerService.select_All_Reader();
        for(Reader reader1:readers){//读者信息注册时readerId不能为空或者重复
            if(reader1.getReaderId().equals(reader.getReaderId())||reader.getReaderId().equals("")){
                return new ModelAndView("readerRegister","message","读者id信息错误");
            }
        }
        if(reader.getPhone().length()>11){//手机号码数限制
            return new ModelAndView("readerRegister","message","电话号码不超过11位");
        }
        Date date=new Date();//将注册时的时间字符串格式化成date类型存至数据库
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        reader.setRegDate(simpleDateFormat.format(date));
        readerService.addReader(reader);//增加读者
        return new ModelAndView("login","message","读者信息注册成功，请使用用户身份登录");
    }

}
